<template>
  <el-dialog :model-value="visible" title="仓库详情" width="800px" :close-on-click-modal="false" @close="handleClose">
    <div class="warehouse-detail">
      <!-- 仓库名称和操作按钮 -->
      <div class="detail-header">
        <div class="warehouse-title">
          <h3>{{ warehouse?.warehouseName || '仓库名称' }}</h3>
          <div class="metadata">
            <p>创建人: {{ warehouse?.createName || '-' }}</p>
            <p>创建时间: {{ formatDateTime(warehouse?.createTime) }}</p>
            <p>最后修改人: {{ warehouse?.modifierName || warehouse?.createName || '-' }}</p>
            <p>修改时间: {{ formatDateTime(warehouse?.modifyTime) || formatDateTime(warehouse?.createTime) }}</p>
          </div>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="handleEdit">
            编辑
          </el-button>
          <el-button type="danger" @click="handleDelete">
            删除
          </el-button>
        </div>
      </div>

      <!-- 仓库详情信息 -->
      <div class="detail-content">
        <div class="section-title">
          <el-icon class="title-icon">
            <InfoFilled />
          </el-icon>
          仓库详情
        </div>

        <div class="section-subtitle">
          <el-icon class="title-icon">
            <InfoFilled />
          </el-icon>
          基础信息
        </div>

        <div class="info-grid">
          <div class="info-column">
            <div class="info-item">
              <span class="info-label">上级名称:</span>
              <span class="info-value">{{ getParentWarehouseName(warehouse?.parentId) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">仓库名称:</span>
              <span class="info-value">{{ warehouse?.warehouseName || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">存储类型:</span>
              <span class="info-value">{{ getStorageTypeName(warehouse?.storageTypeId) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">负责人:</span>
              <span class="info-value">{{ getPersonName(warehouse?.personInChargeId) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">仓库地址:</span>
              <span class="info-value">{{ warehouse?.address || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">备注:</span>
              <span class="info-value">{{ warehouse?.remarks || '-' }}</span>
            </div>
          </div>

          <div class="info-column">
            <div class="info-item">
              <span class="info-label">仓库编号:</span>
              <span class="info-value">{{ warehouse?.warehouseNumber || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">仓库分类:</span>
              <span class="info-value">{{ getCategoryName(warehouse?.categoryId) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">仓库结构:</span>
              <span class="info-value">{{ getStructureName(warehouse?.structureId) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">状态:</span>
              <span class="info-value">
                <el-tag :type="warehouse?.isEnabled ? 'success' : 'danger'" size="small">
                  {{ warehouse?.isEnabled ? '启用' : '禁用' }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import {
  getWarehouseList,
  getAllWarehouseCategories,
  getAllStorageTypes,
  getAllWarehouseStructures,
  getAllPersons
} from '@/Https/server'

// Props
interface Props {
  visible: boolean
  warehouse?: any
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'edit': [warehouse: any]
  'delete': [warehouse: any]
}>()

// 响应式数据
const parentWarehouseOptions = ref<any[]>([])
const categoryOptions = ref<any[]>([])
const storageTypeOptions = ref<any[]>([])
const structureOptions = ref<any[]>([])
const personOptions = ref<any[]>([])

// 计算属性 - 规范化仓库数据
const warehouse = computed(() => {
  if (!props.warehouse) return null
  
  const raw = props.warehouse
  return {
    id: raw.id ?? raw.Id,
    warehouseNumber: raw.warehouseNumber ?? raw.WarehouseNumber,
    warehouseName: raw.warehouseName ?? raw.WarehouseName,
    parentId: raw.parentId ?? raw.ParentId,
    categoryId: raw.categoryId ?? raw.CategoryId,
    storageTypeId: raw.storageTypeId ?? raw.StorageTypeId,
    structureId: raw.structureId ?? raw.StructureId,
    personInChargeId: raw.personInChargeId ?? raw.PersonInChargeId,
    address: raw.address ?? raw.Address ?? '',
    remarks: raw.remarks ?? raw.Remarks ?? '',
    isEnabled: raw.isEnabled ?? raw.IsEnabled ?? true,
    createTime: raw.createTime ?? raw.CreateTime,
    createName: raw.createName ?? raw.CreateName,
    modifyTime: raw.modifyTime ?? raw.ModifyTime,
    modifierName: raw.modifierName ?? raw.ModifierName,
    // 保留显示用的名称字段
    categoryName: raw.categoryName ?? raw.CategoryName,
    storageTypeName: raw.storageTypeName ?? raw.StorageTypeName,
    structureName: raw.structureName ?? raw.StructureName,
    personInChargeName: raw.personInChargeName ?? raw.PersonInChargeName
  }
})

// 方法
const formatDateTime = (dateTime: string | Date) => {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch {
    return dateTime.toString()
  }
}

const getParentWarehouseName = (parentId: number | null) => {
  if (!parentId) return '-'
  const parent = parentWarehouseOptions.value.find(item => 
    item.id === parentId || item.Id === parentId
  )
  return parent?.warehouseName ?? parent?.WarehouseName ?? '-'
}

const getCategoryName = (categoryId: number | null) => {
  if (!categoryId) return '-'
  const category = categoryOptions.value.find(item => 
    item.id === categoryId || item.Id === categoryId
  )
  return category?.categoryName ?? category?.CategoryName ?? '-'
}

const getStorageTypeName = (storageTypeId: number | null) => {
  if (!storageTypeId) return '-'
  const storageType = storageTypeOptions.value.find(item => 
    item.id === storageTypeId || item.Id === storageTypeId
  )
  return storageType?.typeName ?? storageType?.TypeName ?? '-'
}

const getStructureName = (structureId: number | null) => {
  if (!structureId) return '-'
  const structure = structureOptions.value.find(item => 
    item.id === structureId || item.Id === structureId
  )
  return structure?.structureName ?? structure?.StructureName ?? '-'
}

const getPersonName = (personId: number | null) => {
  if (!personId) return '-'
  const person = personOptions.value.find(item => 
    item.id === personId || item.Id === personId
  )
  return person?.personName ?? person?.PersonName ?? person?.name ?? person?.Name ?? person?.userName ?? person?.UserName ?? '-'
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleEdit = () => {
  emit('edit', props.warehouse)
  emit('update:visible', false)
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除仓库"${props.warehouse?.warehouseName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    emit('delete', props.warehouse)
    emit('update:visible', false)
  } catch (error) {
    // 用户取消删除
  }
}

// 加载选项数据
const loadOptions = async () => {
  try {
    console.log('开始加载仓库详情选项数据...')
    
    // 加载上级仓库选项
    const parentResponse: any = await getWarehouseList({ pageSize: 1000 })
    console.log('上级仓库响应:', parentResponse)
    if (parentResponse.success || parentResponse.code === 200 || parentResponse.Code === 200) {
      parentWarehouseOptions.value = parentResponse.data?.pageData ?? parentResponse.data?.PageData ?? parentResponse.data ?? []
      console.log('上级仓库选项加载完成，共', parentWarehouseOptions.value.length, '条')
    }

    // 加载仓库分类选项 - 使用不分页的API
    const categoryResponse: any = await getAllWarehouseCategories()
    console.log('仓库分类响应:', categoryResponse)
    if (categoryResponse.success || categoryResponse.code === 200 || categoryResponse.Code === 200) {
      categoryOptions.value = categoryResponse.data ?? []
      console.log('仓库分类选项加载完成，共', categoryOptions.value.length, '条')
    }

    // 加载存储类型选项 - 使用不分页的API
    const storageTypeResponse: any = await getAllStorageTypes()
    console.log('存储类型响应:', storageTypeResponse)
    if (storageTypeResponse.success || storageTypeResponse.code === 200 || storageTypeResponse.Code === 200) {
      storageTypeOptions.value = storageTypeResponse.data ?? []
      console.log('存储类型选项加载完成，共', storageTypeOptions.value.length, '条')
    }

    // 加载仓库结构选项 - 使用不分页的API
    const structureResponse: any = await getAllWarehouseStructures()
    console.log('仓库结构响应:', structureResponse)
    if (structureResponse.success || structureResponse.code === 200 || structureResponse.Code === 200) {
      structureOptions.value = structureResponse.data ?? []
      console.log('仓库结构选项加载完成，共', structureOptions.value.length, '条')
    }

    // 加载人员选项 - 使用不分页的API
    const personResponse: any = await getAllPersons()
    console.log('人员响应:', personResponse)
    if (personResponse.success || personResponse.code === 200 || personResponse.Code === 200) {
      personOptions.value = personResponse.data ?? []
      console.log('人员选项加载完成，共', personOptions.value.length, '条')
    }
    
    console.log('所有选项数据加载完成')
  } catch (error) {
    console.error('加载选项数据失败:', error)
  }
}

// 监听仓库数据变化，重新加载选项数据
watch(() => props.warehouse, (newWarehouse) => {
  if (newWarehouse && props.visible) {
    console.log('仓库数据变化，重新加载选项数据:', newWarehouse)
    loadOptions()
  }
}, { immediate: true })

// 监听对话框显示状态，显示时加载选项数据
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.warehouse) {
    console.log('对话框显示，加载选项数据')
loadOptions()
  }
})
</script>

<style scoped>
.warehouse-detail {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.warehouse-title h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.metadata p {
  margin: 5px 0;
  color: #909399;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.detail-content {
  background-color: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.section-subtitle {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.info-grid {
  display: flex;
  gap: 40px;
}

.info-column {
  flex: 1;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-label {
  min-width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  color: #303133;
  flex: 1;
}

.dialog-footer {
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-tag) {
  border-radius: 4px;
}
</style>